package com.stylefeng.guns.modular.small.util;

import com.alibaba.fastjson.JSONObject;
import com.stylefeng.guns.core.util.JsonUtils;
import lombok.extern.slf4j.Slf4j;

import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;

@Slf4j
public class SignUtil {

    /**
     * sign 签名 （参数名按ASCII码从小到大排序（字典序）+key+MD5+转大写签名）
     *
     * @return
     */
    public static String createSign(Map params, String key) {

        StringBuffer sbkey = new StringBuffer();
        // entrySet 所有参与传参的参数按照accsii排序（升序）
        // 将参数以参数名的字典升序排序
        Map<String, Object> sortParams = new TreeMap<String, Object>(params);
        Set es = sortParams.entrySet();
        Iterator it = es.iterator();

        while (it.hasNext()) {
            Map.Entry entry = (Map.Entry) it.next();
            String k = (String) entry.getKey();
            Object v = entry.getValue();
            //空值不传递，不参与签名组串
            if (null != v && !"".equals(v)) {
                sbkey.append(k + "=" + v + "&");
            }
        }
        sbkey = sbkey.append("key=" + key);
        if(sbkey.toString().contains("packages"))
            sbkey=new StringBuffer(sbkey.toString().replaceAll("packages","package"));
        log.info("签名前的参数:{}",sbkey);
        //MD5加密,结果转换为大写字符
        return encodeByMD5(sbkey.toString()).toUpperCase();
    }

    /**
     * 对字符串进行MD5加密
     *
     * @param str 需要加密的字符串
     * @return 小写MD5字符串 32位
     */
    public static String encodeByMD5(String str) {
        MessageDigest digest;

        try {
            digest = MessageDigest.getInstance("MD5");
            digest.update(str.getBytes());
            return new BigInteger(1, digest.digest()).toString(16);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 通过签名算法计算得出的签名值，详见签名生成算法
     *@param o
     * @param secret
     * @return sign
     */
    public  static String getSign(Object o, String secret) {
        Map<String, Object> param = JSONObject.parseObject(JsonUtils.toJson(o), Map.class);
        String sign = SignUtil.createSign(param, secret);
        return  sign;
    }

//    wx static void main(String[] args) {
//        SortedMap<String, Object> params = new TreeMap<>();
//        params.put("mid", "39146742");
//        params.put("date", "20190327");
//        params.put("sign", createSign(params, "2EF06B99200B2A213DE9"));
//    }
}
